package org.example.config;

import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author: zk
 * @date: 2023/6/23 17:47
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "redisson")
public class RedissonConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(RedissonConfiguration.class);

    private int timeout = 3000;
    private String schema = "redis://";
    private String address;
    private String password;
    private int connectionPoolSize = 64;
    private int connectionMinimumIdleSize = 10;
    private int slaveConnectionPoolSize = 250;
    private int masterConnectionPoolSize = 250;
    private String[] sentinelAddresses;
    private String masterName;

    /**
     * 哨兵模式
     * @return
     */
    @Bean
    public RedissonClient redissonSentinel() {
        Config config = new Config();

        // 拼接协议
        String[] sentinelAddressesWithSchema = new String[sentinelAddresses.length];
        for (int i = 0; i < sentinelAddresses.length; i++) {
            sentinelAddressesWithSchema[i] = schema + sentinelAddresses[i];
        }

        SentinelServersConfig serversConfig = config.useSentinelServers()
                .setMasterName(masterName)
                .addSentinelAddress(sentinelAddressesWithSchema)
                .setMasterConnectionPoolSize(masterConnectionPoolSize)
                .setSlaveConnectionPoolSize(slaveConnectionPoolSize)
                .setMasterConnectionMinimumIdleSize(getConnectionMinimumIdleSize())
                .setSlaveConnectionMinimumIdleSize(getConnectionMinimumIdleSize())
                .setCheckSentinelsList(false);

        if (StringUtils.hasText(password)) {
            serversConfig.setPassword(password);
        }

        RedissonClient redissonClient = null;
        try {
            redissonClient = Redisson.create(config);
        } catch (Exception e) {
            logger.error("redissonClient 创建失败");
            e.printStackTrace();
        }
        return redissonClient;
    }

    @Bean
    public RBloomFilter<String> bloomFilter() {
        RedissonClient redissonClient = redissonSentinel();
        // 获取布隆过滤器
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("tiny_url_filter");
        // 初始化，容量、误判率
        bloomFilter.tryInit(1000000, 0.01);
        return bloomFilter;
    }

}
